import {
    NextRequest,
    NextResponse
} from 'next/server';
import {
    createTokens,
    verifyToken
} from '@/lib/jwt';
import {
    prisma
} from '@/lib/db';

export async function GET(req: NextRequest) {
    try {
        const refreshToken = req.cookies.get('refresh_token')?.value;
        const redirectUrl = req.nextUrl.searchParams.get('redirect') || '/dashboard';
        if (!refreshToken) {
            return NextResponse.redirect(new URL('/login', req.url));
        }
        const refreshPayload = await verifyToken(refreshToken);
        if (!refreshPayload || !refreshPayload.userId) {
            return NextResponse.redirect(new URL('/login', req.url));
        }
        const userId = refreshPayload.userId as number;
        // 刷新？ 数据库再校验一次
        const user = await prisma.user.findUnique({
            where: {
                id: userId
            }
        });
        if (!user || user?.refreshToken !== refreshToken) {
            return NextResponse.redirect(new URL('/login', req.url));
        }
        const {
            accessToken: newAccessToken,
            refreshToken: newRefreshToken
        } = await createTokens(userId);
        // 刷新成功 数据库更新
        await prisma.user.update({
            where: {
                id: userId
            },
            data: {
                refreshToken: newRefreshToken
            }
        });
        const response = NextResponse.redirect(new URL(redirectUrl, req.url));
        response.cookies.set('access_token', newAccessToken, {
            httpOnly: true,
            maxAge: 60 * 15,
            sameSite: 'strict',
            path: '/'
        });
        response.cookies.set('refresh_token', newRefreshToken, {
            httpOnly: true,
            maxAge: 60 * 60 * 24 * 7,
            sameSite: 'strict',
            path: '/'
        });
        return response;
    } catch (error) {
        console.log('Token refresh error:', error);
        return NextResponse.redirect(new URL('/login', req.url));
    }
}